#include <iostream>
#include <vector>
#include <sstream>
#include <queue>

struct Node
{
    int x;
    int y;
    int t;
};

int direction_vec[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

int main()
{
    std::string s;
    std::vector<std::vector<std::string>> str_map;
    while (std::getline(std::cin, s))
    {
        std::istringstream iss(s);
        std::string token;
        std::vector<std::string> line_vec;
        while (std::getline(iss, token, ' '))
        {
            line_vec.push_back(token);
        }
        str_map.push_back(line_vec);
    }

    std::queue<Node> tq;
    int rows = str_map.size();
    int cols = str_map[0].size();
    std::vector<std::vector<bool>> vis_map(rows, std::vector<bool>(cols, false));
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            if (str_map[i][j] == "YES")
            {
                tq.push({j, i, 0});
                vis_map[i][j] = true;
            }
        }
    }

    int max_t = 0;
    while (!tq.empty())
    {
        Node nd = tq.front();
        tq.pop();
        max_t = nd.t;

        for (int i = 0; i < 4; i++)
        {
            int x = nd.x + direction_vec[i][0];
            int y = nd.y + direction_vec[i][1];
            if (x >= 0 && x < cols && y >= 0 && y < rows && !vis_map[y][x])
            {
                if (str_map[y][x] == "NO")
                {
                    tq.push({x, y, nd.t + 1});
                    str_map[y][x] = "YES";
                }
                vis_map[y][x] = true;
            }
        }
    }

    bool fg = false;
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            if (str_map[i][j] == "NO")
            {
                fg = true;
                break;
            }
        }
    }

    if (fg)
        std::cout << -1 << std::endl;
    else
        std::cout << max_t << std::endl;

    return 0;
}